package com.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.hdb.TGood;


public class Cart {

    protected Map<Integer, OrderItem> items;
    public int totalPrice;
    public Cart() {

        if (items == null) {
            items = new HashMap<>();
        }
    }

    public void goodAdd(TGood good, int count) {
        int goodsId = good.getGoodId();

        if (items.containsKey(goodsId)) {

            OrderItem orderitem = items.get(goodsId);
            orderitem.addCount(count);
            //items.replace(goodsId,orderitem);
        } else {
            items.put(goodsId, new OrderItem(good, count));
        }
        totalPrice = getTotalPrice();
    }

    public void goodDel(Integer goodsId) {
        items.remove(goodsId);
        totalPrice = getTotalPrice();
    }


    public void updateCart(TGood good, int count) {

        OrderItem orderItem = items.get(good.getGoodId());
        orderItem.setCount(count);
        //items.put(goodsId, orderItem);
        totalPrice = getTotalPrice();
    }

    public void updateCart(int goodId, int count) {

        OrderItem orderItem = items.get(goodId);
        orderItem.setCount(count);
        //items.put(goodsId, orderItem);
        totalPrice = getTotalPrice();
    }

    public int getTotalPrice() {

        int totalPrice = 0;
        for (OrderItem orderItem : items.values()) {
            TGood good = orderItem.getGood();
            int count = orderItem.getCount();
            if (good.getGoodType() == 0) {
                totalPrice += good.getGoodPrice() * count;
            } else {
                totalPrice += good.getGoodLowPrice() * count;
            }

        }
        return totalPrice;
    }

    public Map<Integer, OrderItem> getItems() {
        return items;
    }

}
